﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
//using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.IO;
using System.Web;
using System.Collections.Specialized;

using System.Text.RegularExpressions;


using System.Globalization;
using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;

using System.Xml;

using System.Diagnostics;
using Newtonsoft.Json;
using System.Runtime.Remoting.Contexts;


namespace CyberWin.Trade.IDE.Server
{
    public class CyberWin_ServiceMain
    {
        HttpListener httpListener = new HttpListener();

        private string[] agentArray;
        private string[] clientAllowIPArray;

        private string 服务器端口 = "19875";
        private bool is自动运行 = true;

        //应用程序根目录
        private static string CyberWin_ROOT_PATH = Application.StartupPath + "/CyberWinPHP/CyberPHP_Application/";
        //程序根目录
        private static string CyberWin_ROOT_PATH_config = Application.StartupPath + "/CyberWinPHP";
        //服务配置
        static string svrconfig = CyberWin_ROOT_PATH_config + "/CyberPHP_config/svr.cyberphp";
        //app配置
        static string appconfig = CyberWin_ROOT_PATH_config + "/CyberPHP_config/app.cyberphp";

        private XmlDocument app_config_xmlDoc = new XmlDocument();

        private static string cyber_path_applications = CyberWin_ROOT_PATH + "/CyberPHP_Applications";
        private static string cyber_path_core = CyberWin_ROOT_PATH + "/CyberPHP_core";

        //系统日志
        static string log_event = "CyberWin  Net Server";

        static string appName = "";

        private string php_exepath = "";

        public CyberWin_ServiceMain()
        {

        }


        public struct 未来之窗_APP_Config
        {
            public CompilerParameters objCompilerParameters;
            public string code;
            public int 状态;
            public string 信息;
        }

        public void Cyber_Load()
        {
            Cyber_Load(false, (new Button()));
        }
        public void Cyber_Load(bool isNotServices)
        {
            Cyber_Load(isNotServices, (new Button()));
        }
        public void Cyber_Load(bool isNotServices, Control frm_ctrl)
        {
            try
            {


                writesyslog("应用程序启动成功", "1");



               
                string isAutorun = "0";// ir.IniReadValue("svr", "autorun");
                php_exepath = "";// ir.IniReadValue("svr", "php");
                appName = "";// ir.IniReadValue("svr", "appName");

                if (appName != "")
                {
                    log_event = "CyberWin  Net Server" + appName;
                }

                if (isAutorun == "1")
                {
                    is自动运行 = true;
                }
                else
                {
                    is自动运行 = false;
                }


                string svr_port = "2004";// ir.IniReadValue("svr", "port");
                if (svr_port != "")
                {
                    if (int.Parse(svr_port) > 1000)
                    {
                        服务器端口 = svr_port.Trim();
                    }
                }
              //取消  app_config_xmlDoc.Load(appconfig);

                if (is自动运行 == true)
                {
                    // button1_Click(sender, e);
                    // Start();
                    if (isNotServices == true)
                    {
                        Start();
                        // frm_ctrl.Enabled = false;
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                writesyslog("应用程序启动" + ex.Message, "0");
            }

        }


        public void Stop()
        {
            try
            {

                if (httpListener != null)
                {
                    //关闭服务器
                      httpListener.Close();

                      httpListener.Stop();
                      httpListener.Abort();
                     httpListener.Close();
                }

            }
            // catch (System.Net.HttpListenerException ex)
            //  catch (Exception ex)
            //   {
            // CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinPC.Helper.Logger.Log_Engine.write_logV2("systemweb", "ex",ex.Message);

            // CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinOutput.Log.Cyber_Logger.write_log("服务器log", "停止", ex.Message + ex.InnerException);
            //  }
            catch (Exception ex)
            {
                // CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinPC.Helper.Logger.Log_Engine.write_logV2("systemweb", "ex", ex.Message);
               write_log("服务器log", "停止", ex.Message + ex.InnerException);
                //
            }
        }

        //windows 进程操作
        public static string KillWinPro(string token, string processNmae, string exePath)
        {
            // CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinPC.Helper.Logger.Log_Engine.write_logV2("任务日志", token + "-" + "结束进程", "进程名称：" + processNmae + " 路径" + exePath);

            Process[] ps = Process.GetProcessesByName(processNmae);
            string path;

            foreach (Process p in ps)
            {
                path = p.MainModule.FileName.ToString();
                if (exePath.Trim().ToLower().Equals(path.Trim().ToLower()))
                {
                    // this.listBox1.Items.Add(path);
                    p.CloseMainWindow();
                    p.Kill();
                }

            }
            return "进程已经结束";
        }
        public void Start()
        {
            try
            {
                cyberh();

                // button1.Enabled = false;
            }
            catch (Exception ex)
            {

                //  CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinOutput.Log.Cyber_Logger.write_log("服务器log", "start", ex.Message + ex.InnerException);
                //
                write_log("服务器log", "start", ex.Message + ex.InnerException);
            }
        }
        #region "系统cyberh"
        private string getEns(string text)
        {
            return "";// CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberSafe._Encrpt.DESEncrypt.Encrypt(text, "CyberWin-20225578-WLZC-O874-00630UN50HTP");
        }
        private string getDes(string pass)
        {
            return "";// CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberSafe._Encrpt.DESEncrypt.Decrypt(pass, "CyberWin-20225578-WLZC-O874-00630UN50HTP");
        }

        private void cyberh()
        {


            httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            httpListener.Prefixes.Add("http://*:" + 服务器端口 + "/cyberphp/");
            // CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinWeb.Helper.InfoControl.iniFile ir = new CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinWeb.Helper.InfoControl.iniFile(svrconfig);
           /*
            int i = 1;
            int l = 5;
            for (i = 1; i < l; i++)
            {
                string svrsre = "127.0.0.1";// ir.IniReadValue("svr", i.ToString());
                svrsre = svrsre.Trim();
                if (svrsre.Length > 8)
                {
                    httpListener.Prefixes.Add("http://" + svrsre + ":" + 服务器端口 + "/cyberphp/");
                }
            }
            //加载允许IP
            string allow_count = "*";// ir.IniReadValue("sysparam", getEns("allow_count"));
            int l2 = int.Parse(getDes(allow_count));
            clientAllowIPArray = new string[l2];
            //int l2=10;
            for (i = 1; i < l2; i++)
            {
                string svrsre = "*";// ir.IniReadValue("allow_ip", i.ToString());
                svrsre = svrsre.Trim();
                if (svrsre.Length > 0)
                {
                    clientAllowIPArray[i] = svrsre;
                }
            }

            int l3 = 10;
            clientAllowIPArray = new string[l3];
            //int l2=10;
            for (i = 1; i < l3; i++)
            {
                string svrsre = "*";// ir.IniReadValue("allow_agent", i.ToString());
                svrsre = svrsre.Trim();
                if (svrsre.Length > 0)
                {
                    agentArray[i] = svrsre;
                }
            }
            */
            httpListener.Start();

            try
            {

                //  httpListener.BeginGetContext(GetHttpContextCallback, null);

                new Thread(new ThreadStart(delegate
                {
                    while (true)
                    {

                        HttpListenerContext httpListenerContext = httpListener.GetContext();
                        StreamReader reader = new StreamReader(httpListenerContext.Request.InputStream);

                        //httpListenerContext.Request.InputStream.BeginRead(MyBytes, 0, MyBytes.Length, ReadCallback, null);
                        // using (
                        //  Stream stream = new FileStream(SecondSubFolder + MyHttpClsMessage.UploadFileName, FileMode.Append, FileAccess.Write);
                        //)

                        // {

                        //将字符信息写入文件系统

                        //  stream.Write(MyBytes, 0, ReadSize);

                        // });




                        string req = reader.ReadToEnd();

                        string url = httpListenerContext.Request.RawUrl;

                        // string token = httpListenerContext.Request.QueryString["token"];
                        string app = httpListenerContext.Request.QueryString["app"] != null ? httpListenerContext.Request.QueryString["app"] : "";
                        string action = httpListenerContext.Request.QueryString["a"] != null ? httpListenerContext.Request.QueryString["a"] : "";

                        string function = httpListenerContext.Request.QueryString["f"] != null ? httpListenerContext.Request.QueryString["f"] : "";

                        //此功能只正对call_web
                        string cyber_is_解锁输出 = httpListenerContext.Request.QueryString["outputweb"];



                        // CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinPC.Helper.Logger.Log_Engine.write_logV2("systemweb", "run", app + "action=" + action + "function=" + function + "客户端" + url);



                        //HttpListenerContext httpListenerContext = httpListener.GetContext();
                        httpListenerContext.Response.StatusCode = 200;

                        using (StreamWriter writer = new StreamWriter(httpListenerContext.Response.OutputStream))
                        {
                            NameValueCollection d = CyberPHPGetParm(req);

                            //添加输出流内容，like php://input
                            d.Add("CyberPHP->Client://input", req);
                            //  CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinPC.Helper.Logger.Log_Engine.write_logV2("systemweb", "run", "混合=" + req);


                            d.Add("CyberPHP->Client:IP", httpListenerContext.Request.RemoteEndPoint.Address.ToString());
                            d.Add("CyberPHP->Client:Port", httpListenerContext.Request.RemoteEndPoint.Port.ToString());

                            // CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinPC.Helper.Logger.Log_Engine.write_logV2("systemweb", "run", "app=" + app.ToString());

                            if (app.Length < 1)
                            {
                                app = "Cyber_CallWeb";
                                if (action.Length < 1)
                                {
                                    action = "CyberPHP_App";
                                }
                                cyber_is_解锁输出 = "yes";

                            }



                            string 全路径 = httpListenerContext.Request.Url.ToString();
                            int 路径开始 = 全路径.IndexOf("/cyberphp/");

                            // CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinPC.Helper.Logger.Log_Engine.write_logV2("systemweb", "run", app + "action=" + action + "全路径=" + 全路径);


                            if (路径开始 < 0)
                            {
                                //自动补齐/
                                // 全路径
                                全路径 = 全路径 + "/";
                                路径开始 = 全路径.IndexOf("/cyberphp/");
                            }
                            else
                            {
                                d.Add("CyberPHP->Client:URL", 全路径);
                            }

                            int 路径结束 = 全路径.IndexOf("?");

                            if (路径结束 == -1)
                            {
                                路径结束 = 全路径.Length;
                            }
                            string 路径 = 全路径.Substring(路径开始 + 10, 路径结束 - (路径开始 + 10));
                            d.Add("CyberPHP->Client:Path", 路径);

                            //寻找文件名
                            int path_文件名开始 = 全路径.LastIndexOf("/");
                            if (path_文件名开始 != -1)
                            {
                                string client_filename = "";
                                string client_pathwithoutfilename = "";
                                if (path_文件名开始 > 全路径.Length - 2)
                                {
                                    client_filename = "index.cyberphp";
                                    client_pathwithoutfilename = 路径;
                                }
                                else
                                {
                                    client_filename = 全路径.Substring(path_文件名开始 + 1, 路径结束 - (path_文件名开始 + 1));
                                    client_pathwithoutfilename = 路径.Substring(0, 路径.Length - client_filename.Length);// 全路径.Substring(path_文件名开始 + 1, 路径结束 - (path_文件名开始 + 1) - client_filename.Length);
                                }

                                //如果文件路径为空
                                if (client_filename.Length == 0)
                                {
                                    client_filename = "index.cyberphp";
                                }
                                d.Add("CyberPHP->Client:FileName", client_filename);
                                d.Add("CyberPHP->Client:PathWithOutFileName", client_pathwithoutfilename);
                            }
                            else
                            {
                                d.Add("CyberPHP->Client:FileName", "index.cyberphp");
                            }
                            //获取域名domain
                            // 路径开始
                            string url_domain = 全路径.Substring("http://".Length, 路径开始 - "http://".Length);
                            d.Add("CyberPHP->Client:Domain", url_domain);
                            //路径不带文件名





                            string 客户端_UserAgent = "";
                            try
                            {
                                客户端_UserAgent = httpListenerContext.Request.UserAgent;
                                if (客户端_UserAgent == null)
                                {
                                    客户端_UserAgent = "";
                                }

                            }
                            catch (Exception ex)
                            {
                                客户端_UserAgent = "";
                            }
                            //未来之窗方行2020-3-15
                            if (客户端_UserAgent.IndexOf("CyberWin WebBrowser") > 0)
                            {
                                客户端_UserAgent = "";
                            }


                            d.Add("CyberPHP->Client:UserAgent", httpListenerContext.Request.UserAgent);
                            d.Add("CyberPHP->Client:UserHostName", httpListenerContext.Request.UserHostName);
                            //  d.Add("CyberPHP->Client:UserLanguages", httpListenerContext.Request.UserLanguages.ToString());

                            //授权Agent
                            if (isAgent(客户端_UserAgent) == false)
                            {
                                if (客户端_UserAgent.ToLower() != "")
                                {


                                    if (cyber_is_解锁输出 != null && app.Equals("Cyber_CallWeb"))
                                    {
                                        if (cyber_is_解锁输出.Equals("yes"))
                                        {
                                            app = "Cyber_CallWeb";
                                        }
                                        else
                                        {
                                            app = "cyberphp_abort_for";
                                        }
                                    }
                                    else
                                    {
                                        app = "cyberphp_abort_for";
                                    }
                                }
                            }



                           write_log("systemweb", "run", "开始插件前=" + app + "  ac=" + action);


                            Object cyber_ret = "";
                            switch (app)
                            {
                                case "cyberphp_abort_for":
                                    {
                                        cyber_ret = CyberAbort();
                                    }
                                    break;
                                case "weixin":
                                    {

                                        //  TencentQy tqy = new CyberWin.CSHARP.HRKJ.Trade.Net.Server.LW.CyberApp.Tencent.TencentQy();
                                        //  cyber_ret = tqy.handle(action, d);
                                        // writer.Write(handle_ret);

                                    }
                                    break;
                                case "pushNO":
                                    {
                                        cyber_ret = CyberDefault(d);
                                    }
                                    break;
                                case "Cyber_CallApp":
                                    {
                                        // NameValueCollection n = new NameValueCollection();
                                        // n.Add("dd", "这个是我传过去的");
                                        //   CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinPC.Helper.Logger.Log_Engine.write_logV2("systemweb", "run", "插件=" + action + "function=" + function);

                                        cyber_ret = (string)this.Cyber_CallApp(action, function, d);
                                    }
                                    break;


                                case "Cyber_CallWeb":
                                    {
                                        // NameValueCollection n = new NameValueCollection();
                                        // n.Add("dd", "这个是我传过去的");
                                        //  CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinPC.Helper.Logger.Log_Engine.write_logV2("systemweb", "run", "2024网页=" + action + "  function = " + function);
                                        //   httpListenerContext.Response.
                                        //2023-8-6
                                        //d.Get("CyberPHP->Client:FileName")
                                        //Cyber_CallWeb
                                       // cyber_ret = this.Cyber_CallWeb(action, d);
                                        //httpListenerContext.Response.ContentLength64 = 15;
                                        //(string)
                                        String 文件后缀 = System.IO.Path.GetExtension(d.Get("CyberPHP->Client:FileName"));
                                        // Log_Engine.write_logV2("systemweb", "run", "文件后缀=" + 文件后缀 + "  ac=" + action);
                                        String 文件后缀响应 = "application/octet-stream";
                                        /*
                                        switch (文件后缀)
                                        {
                                            case ".html":
                                                文件后缀响应 = "text/html";
                                                break;
                                            case ".htm":
                                                文件后缀响应 = "text/html";
                                                break;
                                            case ".js":
                                                文件后缀响应 = "application/javascript";
                                                break;
                                            case ".css":
                                                文件后缀响应 = "text/css";
                                                break;
                                            case ".jpg":
                                                文件后缀响应 = "image/jpeg";
                                                break;
                                            case ".bmp":
                                                文件后缀响应 = "image/bmp";
                                                break;
                                            case ".png":
                                                文件后缀响应 = "image/png";
                                                break;
                                            case ".svg":
                                                文件后缀响应 = "image/svg+xml";
                                                break;
                                            case ".json":
                                                文件后缀响应 = "application/json";
                                                break;

                                        }
                                        */
                                        //  string action = httpListenerContext.Request.QueryString["a"] 
                                        cyber_ret = "ffffff";
                                        //HttpListenerContext.Request 客户端 = httpListenerContext.Request;
                                        // .QueryString["a"];

                                        // 从请求的输入流中读取数据

                                        string 命令 = httpListenerContext.Request.QueryString["action"];
                                        string server = httpListenerContext.Request.QueryString["server"];
                                        string table = httpListenerContext.Request.QueryString["table"];
                                        string param1 = httpListenerContext.Request.QueryString["param1"];

                                        string platform_id = httpListenerContext.Request.QueryString["platform_id"];
                                        
                                        string dac_local_database = httpListenerContext.Request.QueryString["dac_local_database"];



                                        // 解析参数
                                        var paramPairs = req.Split('&');
                                            foreach (var paramPair in paramPairs)
                                            {
                                            write_log("systemweb", "paramPair", paramPair);

                                            var keyValue = paramPair.Split('=');
                                                if (keyValue.Length == 2)
                                                {
                                                    Console.WriteLine($"{keyValue[0]}: {keyValue[1]}");
                                                    write_log("systemweb", "参数", "keyValue=" + keyValue[0] + "  keyValue=" + keyValue[1]);
                                                string 参数名称 =  keyValue[0];
                                                string 内容 = keyValue[1];
                                                // 内容 = UrlDecodeUtf8解码(内容);
                                                string 新内容 = Uri.UnescapeDataString(内容);
                                                //HttpUtility.UrlDecode(encodedString);
                                                if (参数名称.Equals("action"))
                                                {
                                                    命令 = 新内容;
                                                }
                                                if (参数名称.Equals("server"))
                                                {
                                                    server = 新内容;
                                                }
                                                if (参数名称.Equals("table"))
                                                {
                                                    table = 新内容;
                                                }
                                                if (参数名称.Equals("param1"))
                                                {
                                                    //++++%3C%3Fphp%0D%0A+++%0D%0A
                                                    //+号乱码
                                                    string 加号号乱码 = 内容.Replace("+", "%20");
                                                    string 加号号乱码str = Uri.UnescapeDataString(加号号乱码);

                                                    param1 = 加号号乱码str;
                                                }
                                                
                                            }
                                            }
                                      

                                       

                                       // string param1 = httpListenerContext.Request.;
                                        cyber_ret = 东方仙盟_ide(platform_id, dac_local_database, 命令, server, table, param1);
                                        //cyber_ret = "ffffff";
                                        文件后缀响应 = "text/html";
                                        文件后缀响应 = "application/json";
                                        httpListenerContext.Response.ContentType = 文件后缀响应;

                                        httpListenerContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");
                                        //  Log_Engine.write_logV2("systemweb", "run", "文件后缀=" + 文件后缀 + "  文件后缀响应=" + 文件后缀响应);


                                    }
                                    break;
                                default:
                                    {
                                        cyber_ret = CyberDefault(d);
                                    }
                                    break;

                            }
                            try
                            {
                                // writer.Write(cyber_ret);
                                if (cyber_ret is System.Byte[])
                                {
                                    System.Byte[] out_b = (byte[])cyber_ret;
                                    httpListenerContext.Response.ContentLength64 = out_b.Length;

                                    httpListenerContext.Response.OutputStream.Write(out_b, 0, out_b.Length);
                                }
                                else
                                {
                                    writer.Write(cyber_ret);
                                }
                            }
                            catch (System.IO.IOException ex)
                            {
                                //回写错误
                                writesyslog("服务器响应失败", "1");


                            }

                        }
                    }
                })).Start();
            }
            catch (Exception ex)
            {

            }

        }
        public string 东方仙盟_ide(string platform_id,string dac_local_database, string 命令, string server, string table, string param1)
        {
            write_log("systemweb", "run", "命令=" + 命令 + "  server=" + server + "  table=" + table + "  param1=" + param1);
            //string action = httpListenerContext.Request.QueryString["a"]
            string 未来之窗ret = "";

            未来之窗通用返回 retobj = new 未来之窗通用返回();
            retobj.status = "9";
            retobj.message = "clien"+ 命令;
            retobj.data = "cliendaa";
           // 未来之窗ret= JsonConvert.SerializeObject(retobj);

           // DA_远程交互_file预览文件Preview
            //G:\未来之窗源码备份\visaulstudio\CyberWin.Trade.IDE.Server\CyberWin.Trade.IDE.Server\bin\Release\code
            if (命令.Equals("DA_远程交互_file预览文件Preview"))
            {
                retobj.data = 东方仙盟_ide_列举文件夹和文件(server, param1) ;
                retobj.message = "list文件夹和文件";
            }
            //DA_远程交互_file读取文件Preview
            if (命令.Equals("DA_远程交互_file读取文件Preview"))
            {
                //platform_id
                cl_东方仙盟_ide个性化数据.ide_add历史(platform_id, dac_local_database, "默认", "file", server);


                retobj.data = 东方仙盟_ide_读取ReadTextFile(server);
                //datatypecode
                //$未来之窗返回ret['datatypecode']="ace/mode/php";
                string 文件扩展_带点号 = Path.GetExtension(server);
                string 文件扩展 = 文件扩展_带点号;
                if (文件扩展_带点号.Length > 1)
                {
                    文件扩展 = 文件扩展_带点号.Substring(1);
                }
                //javascript
                if (文件扩展.Equals("js")==true)
                {
                    文件扩展 = "javascript";
                }

                retobj.datatypecode = "ace/mode/" + 文件扩展;

                retobj.message = "list文件夹和文件";
            }
            //retobj.message = retobj.message + 命令;

            //DA_远程交互_file保存文件Preview
            if (命令.Equals("DA_远程交互_file保存文件Preview"))
            {
                //table: backupfile
                //newfile
                //newfolder
                switch (table)
                {
                    case "backupfile":
                        {
                            if (System.IO.File.Exists(server) == false)
                            {
                                retobj.message = "文件已经不存在，不可备份";
                            }
                            else
                            {
                                string 文件扩展_带点号 = Path.GetExtension(server);
                                string 文件名 = Path.GetFileName(server);
                                string 文件路径 = Path.GetDirectoryName(server);

                                文件路径 = 文件路径 + "/" + "_CWID备份";
                                if (System.IO.Directory.Exists(文件路径) == false)
                                {
                                    Directory.CreateDirectory(文件路径);
                                }


                                string 文件路径_新路径 = 文件路径 + "/" + 文件名 + "_备份" + DateTime.Now.ToString("yyyy年MM月dd日HH时mm分ss秒") + 文件扩展_带点号;

                                File.Copy(server, 文件路径_新路径, true);  // true 表示如果目标文件已存在则覆盖
                                retobj.message = "备份文件";
                            }
                        }
                        break;
                    case "newfile":
                        {
                            if (System.IO.File.Exists(server) == true)
                            {
                                retobj.message = "文件已经存在，不可新建";
                            }
                            else
                            {
                                using (StreamWriter writer = new StreamWriter(server))
                                {
                                    writer.Write(param1);
                                }
                                retobj.message = "新建文件";
                            }
                        }
                        break;
                    case "newfolder":
                        {
                            Directory.CreateDirectory(server);
                            retobj.message = "创建文件夹";
                        }
                        break;

                    case "savefile":
                        {
                            if (System.IO.File.Exists(server) == false)
                            {
                                retobj.message = "文件已经不存在，不可保存";
                            }
                            else
                            {
                                using (StreamWriter writer = new StreamWriter(server))
                                {
                                    writer.Write(param1);
                                }
                                retobj.message = "保存文件";
                            }
                        }
                        break;


                    case "backupandsavefile":
                        {
                            if (System.IO.File.Exists(server) == false)
                            {
                                retobj.message = "文件已经不存在，操作";
                            }
                            else
                            {
                                string 文件扩展_带点号 = Path.GetExtension(server);
                                string 文件名 = Path.GetFileName(server);
                                string 文件路径 = Path.GetDirectoryName(server);

                                文件路径 = 文件路径 + "/" + "_CWIDauto备份";
                                if (System.IO.Directory.Exists(文件路径) == false)
                                {
                                    Directory.CreateDirectory(文件路径);
                                }


                                string 文件路径_新路径 = 文件路径 + "/" + 文件名 + "_备份" + DateTime.Now.ToString("yyyy年MM月dd日HH时mm分ss秒") + 文件扩展_带点号;

                                File.Copy(server, 文件路径_新路径, true);  // true 表示如果目标文件已存在则覆盖
                                using (StreamWriter writer = new StreamWriter(server))
                                {
                                    writer.Write(param1);
                                }
                                retobj.message = "备份和保存文件";
                            }
                        }
                        break;



                }

            }
            try
            {
                if (命令.Equals("DA_远程交互_IDE收藏"))
                {
                    //table: backupfile
                    //newfile
                    //newfolder
                    switch (table)
                    {
                        case "addfavourite":
                            {
                                //string[] 收藏夹 = param1.Split('>');
                                //未来之窗_ide_通用 收藏夹 = (未来之窗_ide_通用)JsonConvert.DeserializeObject(param1);
                                //Person person = JsonConvert.DeserializeObject<Person>(jsonString);
                                未来之窗_ide_通用 收藏夹 = JsonConvert.DeserializeObject<未来之窗_ide_通用>(param1);
                                cl_东方仙盟_ide个性化数据.ide_add收藏(收藏夹.token, 收藏夹.项目, 收藏夹.标题, 收藏夹.类型, 收藏夹.路径);
                                retobj.message = "收藏文件";
                            }
                            break;

                        case "getallfavourite":
                            {
                                //string[] 收藏夹 = param1.Split('>');
                                //未来之窗_ide_通用 收藏夹 = (未来之窗_ide_通用)JsonConvert.DeserializeObject(param1);
                                //Person person = JsonConvert.DeserializeObject<Person>(jsonString);
                                未来之窗_ide_通用 收藏夹 = JsonConvert.DeserializeObject<未来之窗_ide_通用>(param1);
                                retobj.data = cl_东方仙盟_ide个性化数据.ide_get收藏(收藏夹.token, 收藏夹.项目, 收藏夹.标题, 收藏夹.类型, 收藏夹.路径);
                                retobj.message = "get收藏文件";
                            }
                            break;
                        case "delfavourite":
                            {
                                //string[] 收藏夹 = param1.Split('>');
                                //未来之窗_ide_通用 收藏夹 = (未来之窗_ide_通用)JsonConvert.DeserializeObject(param1);
                                //Person person = JsonConvert.DeserializeObject<Person>(jsonString);
                                未来之窗_ide_通用 收藏夹 = JsonConvert.DeserializeObject<未来之窗_ide_通用>(param1);
                                 cl_东方仙盟_ide个性化数据.ide_del收藏(收藏夹.token, 收藏夹.项目);
                                retobj.message = "del收藏文件";
                            }
                            break;
                    }
                }
            }
            catch (Exception ex)
            {

                write_log("未来之窗ide", "excep", "命令=" + 命令 + "  server=" + server + "  table=" + table + "  param1=" + param1+ ex.Message);

            }

            未来之窗ret = JsonConvert.SerializeObject(retobj);

            return 未来之窗ret;
        }

        static string 东方仙盟_ide_列举文件夹和文件(string path,string 返回类型)
        {
            StringBuilder fileData = new StringBuilder();

            未来之窗_ide_通用[] 东方仙盟所有ret = new 未来之窗_ide_通用[1];


            try
            {
                string[] 文件夹列表 = Directory.GetDirectories(path);
                string[] 文件列表 = Directory.GetFiles(path);
                int 文件总数 = 文件夹列表.Length + 文件列表.Length;
                  东方仙盟所有ret= new 未来之窗_ide_通用[文件总数];
                int 文件序数 = 0;


                foreach (string directory in 文件夹列表)
                {
                    //取消顶层跟随
                    //fileData.Append($"<option value='cyber-folder:{directory}/{directory}'>{directory}</option>");
                    //只要一层  fileData.Append(ListFilesAndFolders(directory));
                    string 文件夹名 = Path.GetDirectoryName(directory);

                    string 文件夹名2 = Path.GetFileName(directory);

                    未来之窗_ide_通用 东方仙盟类型one= new 未来之窗_ide_通用();
                    东方仙盟类型one.标题 = 文件夹名2;
                    东方仙盟类型one.路径 = directory;
                    东方仙盟类型one.类型 = "folder";
                    东方仙盟类型one.token = "wlzc";
                    东方仙盟所有ret[文件序数] = 东方仙盟类型one;
                    文件序数 = 文件序数 + 1;

                    fileData.Append($"<option value='cyber-folder:{directory}'>[文件夹]{文件夹名2}</option>");

                }

                foreach (string file in 文件列表)
                {
                    // fileData.Append($"<option value='cyber-file:{path}/{file}'>{file}</option>");
                    string 文件扩展_带点号 = Path.GetExtension(file);
                    string 文件名 = Path.GetFileName(file);
                    string 文件路径 = Path.GetDirectoryName(file);

                    fileData.Append($"<option value='cyber-file:{file}'>{文件名}</option>");

                    未来之窗_ide_通用 东方仙盟类型one = new 未来之窗_ide_通用();
                    东方仙盟类型one.标题 = 文件名;
                    东方仙盟类型one.路径 = file;
                    东方仙盟类型one.类型 = "file";
                    东方仙盟类型one.token = "wlzc";
                    东方仙盟所有ret[文件序数] = 东方仙盟类型one;
                    文件序数 = 文件序数 + 1;

                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }

            if (返回类型.Equals("json"))
            {
                string 未来之窗ret = JsonConvert.SerializeObject(东方仙盟所有ret);
                return 未来之窗ret;
            }
            return fileData.ToString();
        }

        static string 东方仙盟_ide_读取ReadTextFile(string filePath)
        {
            try
            {
                if (System.IO.File.Exists(filePath) == false)
                {
                    return "文件不存在-error";
                }
                using (StreamReader reader = new StreamReader(filePath))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
                return null;
            }
        }

        public bool isAgent(string agent)
        {
            try
            {
                // 遍历数组输出
                foreach (string ai in clientAllowIPArray)
                {
                    if (ai != null)
                    {
                        string a1 = ai.Trim().ToLower();
                        string a2 = agent.Trim().ToLower();
                        if (a1 == a2)
                        {
                            return true;
                        }
                    }

                }
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }


        }
        //php 执行
        public string Cyber_CallPHPWeb(string filename, NameValueCollection d)
        {

            if (System.IO.File.Exists(this.php_exepath) == false)
            {
                return formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
            }
            using (Process process = new System.Diagnostics.Process())
            {
                process.StartInfo.FileName = this.php_exepath;//"ping";
                process.StartInfo.Arguments = " -f \"" + filename + "\"";
                // 必须禁用操作系统外壳程序  
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.RedirectStandardOutput = true;

                process.Start();

                string output = process.StandardOutput.ReadToEnd();

                if (String.IsNullOrEmpty(output) == false)
                    // this.textBox1.AppendText(output + "\r\n");
                    return output;

                process.WaitForExit(30000);
                process.Close();

                return formatError("9009", "执行超时", "Fatal error: Maximum execution time of 30 seconds exceeded in ");
            }
        }

        public string formatError(string code, string title, string descript)
        {
            string errstr = "";// Properties.Settings.Default.inner_error_style;
            errstr = errstr.Replace("{cyber_error:code}", code);
            errstr = errstr.Replace("{cyber_error:title}", title);
            errstr = errstr.Replace("{cyber_error:descript}", descript);
            return errstr;
        }
        //执行网页解析
        public object Cyber_CallWeb(string action, NameValueCollection d)
        {
            string 网络路径 = "";
            string 物理映射路径 = "";
            string cwpd自定义404 = "";

            //获取扩展名称
            string ext文件 = "";
            try
            {

                //      ret = ret + "<li>文件名：" + d.Get("CyberPHP->Client:FileName") + "</li>";
                //  ret = ret + "<li>不含文件路径：" + d.Get("CyberPHP->Client:PathWithOutFileName") + "</li>";
                //  ret = ret + "<li>域名：" + d.Get("CyberPHP->Client:Domain") + "</li>";


                XmlNodeList cyberwin_inclist = app_config_xmlDoc.SelectNodes("/cyberwin/cyberwin_applications/app"); //获取person子节点集合  



                网络路径 = d.Get("CyberPHP->Client:PathWithOutFileName") + d.Get("CyberPHP->Client:FileName");

                foreach (XmlNode node in cyberwin_inclist)
                {
                    string app_name = ((XmlElement)node).GetAttribute("name");   //获取name属性值  
                    if (app_name.Trim().ToLower() == action.Trim().ToLower())
                    {
                        XmlNode xmlNode_物理映射路径节点 = ((XmlElement)node).SelectSingleNode("application/virtualDirectory");

                        物理映射路径 = xmlNode_物理映射路径节点.Attributes["physicalPath"].Value.ToString().Trim();
                        try
                        {
                            cwpd自定义404 = xmlNode_物理映射路径节点.Attributes["e404"].Value.ToString().Trim();

                        }
                        catch (Exception ex)
                        {
                            cwpd自定义404 = "";
                        }
                        //CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinPC.Helper.Logger.Log_Engine.write_logV2("systemweb", "run", "虚拟路径+物理映射路径=" + 物理映射路径);
                        continue;
                    }
                }
                物理映射路径 = 物理映射路径.Replace("{cyberphp_applications}", cyber_path_applications);

                // CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinPC.Helper.Logger.Log_Engine.write_logV2("systemweb", "run", "虚拟路径+物理映射路径=" + 物理映射路径);

                string 文件路径 = 物理映射路径 + 网络路径;

                // CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinPC.Helper.Logger.Log_Engine.write_logV2("systemweb", "run", "虚拟路径+网络路径=" + 网络路径);

                //  CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinPC.Helper.Logger.Log_Engine.write_logV2("systemweb", "run", "虚拟路径+文件路径=" + 文件路径);


                if (System.IO.File.Exists(文件路径) == false)
                {
                    string 文件路径404 = 物理映射路径 + "/" + cwpd自定义404;
                    if (System.IO.File.Exists(文件路径404) == false)
                    {
                        return "404cyberw";// Properties.Settings.Default.inner_error_404;
                    }
                    else
                    {
                        文件路径 = 文件路径404;
                    }



                }




                object cyber_callweb_result = "";
                //获取扩展名称
                ext文件 = System.IO.Path.GetExtension(文件路径);
                if (ext文件.ToLower().Equals(".php") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_CallPHPWeb(文件路径, d);
                }
                else if (ext文件.ToLower().Equals(".js") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_Bin(文件路径);
                }

                else if (ext文件.ToLower().Equals(".jpg") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_Bin(文件路径);
                }
                else if (ext文件.ToLower().Equals(".exe") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_Bin(文件路径);
                }
                else if (ext文件.ToLower().Equals(".zip") == true)
                {
                    cyber_callweb_result = Cyber_GetFile_Bin(文件路径);
                }
                else if (ext文件.ToLower().Equals(".rar") == true)
                {
                    cyber_callweb_result = Cyber_GetFile_Bin(文件路径);
                }
                else if (ext文件.ToLower().Equals(".tar") == true)
                {
                    cyber_callweb_result = Cyber_GetFile_Bin(文件路径);
                }
                else if (ext文件.ToLower().Equals(".gzip") == true)
                {
                    cyber_callweb_result = Cyber_GetFile_Bin(文件路径);
                }
                else if (ext文件.ToLower().Equals(".xml") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_Bin(文件路径);
                }
                else if (ext文件.ToLower().Equals(".cyberphp") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_Bin(文件路径);
                }
                else if (ext文件.ToLower().Equals(".wav") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_Bin(文件路径);
                }
                else if (ext文件.ToLower().Equals(".pdf") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_Bin(文件路径);
                }
                else if (ext文件.ToLower().Equals(".bmp") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_Bin(文件路径);
                }
                else if (ext文件.ToLower().Equals(".png") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_Bin(文件路径);
                }
                else if (ext文件.ToLower().Equals(".txt") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_TXT(文件路径);
                }
                else if (ext文件.ToLower().Equals(".html") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_TXT(文件路径);
                }
                else if (ext文件.ToLower().Equals(".htm") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_TXT(文件路径);
                }
                else if (ext文件.ToLower().Equals(".xml") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_TXT(文件路径);
                }
                else if (ext文件.ToLower().Equals(".vbs") == true)
                {
                    // return "php";// formatError("9005", "系统引擎解析失败", "CyberWin DotnetPHP 服务器引擎丢失！");
                    cyber_callweb_result = Cyber_GetFile_TXT(文件路径);
                }
                else
                {

                    StreamReader fileStream = new StreamReader(文件路径, Encoding.Default);
                    string FileContent = fileStream.ReadToEnd();
                    fileStream.Close();
                    cyber_callweb_result = FileContent;
                }

                //"wait for dev物理映射路径=>" + 物理映射路径 + "  网络路径=>" + 网络路径 +
                return cyber_callweb_result;
            }
            catch (System.IO.IOException ex)
            {
                writesyslog("Cyber_CallWeb IOEX" + ex.Message, "0");
                return "CyberPHP->ERROR::+parsetype=>" + ext文件 + "" + ex.Message + " InnerException:" + ex.InnerException + " Source:" + ex.Source;
            }
            catch (Exception ex)
            {
                writesyslog("Cyber_CallWeb EX" + ex.Message, "0");
                return "CyberPHP->ERROR::+parsetype=>" + ext文件 + "" + ex.Message + " InnerException:" + ex.InnerException + " Source:" + ex.Source;
            }

        }
        public string Cyber_GetFile_TXT(string 文件路径)
        {
            StreamReader fileStream = new StreamReader(文件路径, Encoding.Default);
            string FileContent = fileStream.ReadToEnd();
            fileStream.Close();
            return FileContent;
        }
        //读取文件格式
        public byte[] Cyber_GetFile_Bin(string imagepath)
        {
            /**/
            ////根据图片文件的路径使用文件流打开，并保存为byte[] 
            FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重载方法 
            byte[] byData = new byte[fs.Length];
            fs.Read(byData, 0, byData.Length);
            fs.Close();
            return byData;
        }

        public string Cyber_模块授权(string action, string function, NameValueCollection d)
        {
            // string lic_path = Application.StartupPath + "/CyberWinPHP/CyberWin_Licence/" + action + "_lic.cyberphp";
            string lic_path = CyberWin_ROOT_PATH + "/CyberWin_Licence/" + action + "_lic.cyberphp";

            //Cyber_TokenKey.CL_Token myct = new Cyber_TokenKey.CL_Token();
            //return myct.Cyber_VeryTokenLocalOfflineNotHardWareLockModuleV1("", "", true, false, lic_path, action, "");

            return "1";
        }
        //app
        public object Cyber_CallApp(string action, string function, NameValueCollection d)
        {

            //模块授权
            string 模块授权 = Cyber_模块授权(action, function, d);
            if (模块授权.Equals("1") == false)
            {
                return "CyberPHP->EXPIRE:" + 模块授权;
            }


            /*
            if (function == "")
            {
                function = "start";
            }
            */

            //判断缓存，并加载缓存
            if (Cyber_CallisHaveCache(action) == true)
            {
                return Cyber_CallAppCache(action, function, d);
            }

            //不存在缓存的条件
            try
            {
                // '


                // 1.CSharpCodePrivoder
                CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();

                // 2.ICodeComplier
                ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler();
                /*
                         // 3.CompilerParameters

                         CompilerParameters objCompilerParameters = new CompilerParameters();
                         objCompilerParameters.ReferencedAssemblies.Add("System.dll");

                         int i = 1;
                         int l = 1000;
                         string configPath = Application.StartupPath + "/CyberPHP_App/" + action + "_config.cyberphp";
                         if (System.IO.File.Exists(configPath) == false)
                         {
                             l = 1;
                         }

                         CyberWin.CSHARP.HRKJ.WebFrame.CyberPHP.CyberWinWeb.Helper.InfoControl.iniFile ir = new CyberWin.CSHARP.HRKJ.WebFrame.CyberPHP.CyberWinWeb.Helper.InfoControl.iniFile(configPath);
                         for (i = 1; i < l; i++)
                         {
                             //ir.
                             string libstr = ir.IniReadValue("include", i.ToString());// ir.GetINI("include", i.ToString(), "", configPath);
                             libstr = libstr.Replace("{cyberphp_core}", Application.StartupPath + "/CyberPHP_core");
                             if (libstr.Length < 3)
                             {
                                 break;
                             }
                             else
                             {
                                 objCompilerParameters.ReferencedAssemblies.Add(libstr);
                             }
                         }
                         objCompilerParameters.GenerateExecutable = false;
                         objCompilerParameters.GenerateInMemory = true;

                         // 4.CompilerResults
                         //4.1
                         string codepath = Application.StartupPath + "/CyberPHP_App/" + action + "_app.cyberphp";
                         if (System.IO.File.Exists(codepath) == false)
                         {
                             return "CyberPHP->ERROR:错误的调用";
                         }
                         StreamReader fileStream = new StreamReader(codepath, Encoding.Default);
                         string code = fileStream.ReadToEnd();
                         fileStream.Close();
                          * */
                /*
                未来之窗_APP_Config app_config = Cyber_CallAppV2Loading(action);
                if (app_config.状态 != 1)
                {
                    return app_config.信息;
                }
                */

                // CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, code);
                //设置输出
                string cache_path = CyberWin_ROOT_PATH + "/CyberPHP_Cache/" + action + "_cache.cyberphp";
                // app_config.objCompilerParameters.OutputAssembly = cache_path;

                // CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(app_config.objCompilerParameters, app_config.code);
                /*
                 if (cr.Errors.HasErrors)
                 {
                     Console.WriteLine("编译错误：");
                     string errstr = "CyberPHP->ERROR:An error ocular at App run,For Detail is";
                     foreach (CompilerError err in cr.Errors)
                     {
                         Console.WriteLine(err.ErrorText);
                         errstr = errstr + "Error_code" + err.ErrorNumber + " line  is " + err.Line + err.ErrorText + " at File " + err.FileName;

                     }
                     return errstr;
                 }
                 else
                 {
                     // 通过反射，调用HelloWorld的实例
                     Assembly objAssembly = cr.CompiledAssembly;

                     object objHelloWorld = objAssembly.CreateInstance("CyberPHP_Dynamic.APP");
                     MethodInfo objMI = objHelloWorld.GetType().GetMethod(function);

                     //Console.WriteLine(objMI.Invoke(objHelloWorld, null));
                     object[] p = new object[1];
                     p[0] = d;
                     return objMI.Invoke(objHelloWorld, p);

                 }
                 */
                return "";
            }
            catch (Exception ex)
            {
                return "CyberPHP->ERROR::" + ex.Message + " InnerException:" + ex.InnerException + " Source:" + ex.Source;
            }

        }



        public object Cyber_CallApp_V0(string action, string function, NameValueCollection d)
        {
            if (function == "")
            {
                function = "start";
            }

            try
            {

                // 1.CSharpCodePrivoder
                CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();

                // 2.ICodeComplier
                ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler();

                // 3.CompilerParameters
                CompilerParameters objCompilerParameters = new CompilerParameters();
                objCompilerParameters.ReferencedAssemblies.Add("System.dll");

                int i = 1;
                int l = 1000;
                string configPath = CyberWin_ROOT_PATH + "/CyberPHP_App/" + action + "_config.cyberphp";
                if (System.IO.File.Exists(configPath) == false)
                {
                    l = 1;
                }

                // CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinWeb.Helper.InfoControl.iniFile ir = new CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinWeb.Helper.InfoControl.iniFile(configPath);
                for (i = 1; i < l; i++)
                {
                    //ir.
                    string libstr = "";// ir.IniReadValue("include", i.ToString());// ir.GetINI("include", i.ToString(), "", configPath);
                    libstr = libstr.Replace("{cyberphp_core}", CyberWin_ROOT_PATH + "/CyberPHP_core");
                    if (libstr.Length < 3)
                    {
                        break;
                    }
                    else
                    {
                        objCompilerParameters.ReferencedAssemblies.Add(libstr);
                    }
                }
                objCompilerParameters.GenerateExecutable = false;
                objCompilerParameters.GenerateInMemory = true;

                // 4.CompilerResults
                //4.1
                string codepath = CyberWin_ROOT_PATH + "/CyberPHP_App/" + action + "_app.cyberphp";
                if (System.IO.File.Exists(codepath) == false)
                {
                    return "CyberPHP->ERROR:错误的调用";
                }
                StreamReader fileStream = new StreamReader(codepath, Encoding.Default);
                string code = fileStream.ReadToEnd();
                fileStream.Close();
                CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, code);

                if (cr.Errors.HasErrors)
                {
                    Console.WriteLine("编译错误：");
                    string errstr = "CyberPHP->ERROR:An error ocular at App run,For Detail is";
                    foreach (CompilerError err in cr.Errors)
                    {
                        Console.WriteLine(err.ErrorText);
                        errstr = errstr + "Error_code" + err.ErrorNumber + " line  is " + err.Line + err.ErrorText + " at File " + err.FileName;

                    }
                    return errstr;
                }
                else
                {
                    // 通过反射，调用HelloWorld的实例
                    Assembly objAssembly = cr.CompiledAssembly;
                    object objHelloWorld = objAssembly.CreateInstance("CyberPHP_Dynamic.APP");
                    MethodInfo objMI = objHelloWorld.GetType().GetMethod(function);

                    //Console.WriteLine(objMI.Invoke(objHelloWorld, null));
                    object[] p = new object[1];
                    p[0] = d;
                    return objMI.Invoke(objHelloWorld, p);

                }
            }
            catch (Exception ex)
            {
                return "CyberPHP->ERROR::" + ex.Message + " InnerException:" + ex.InnerException + " Source:" + ex.Source;
            }

        }
        public string CyberAbort()
        {
            string ret = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><title>CyberPHP Handle Server Abort </title></head><body><center><h1>未来之窗软件服务中心-服务器</h1><hr>CopyRight Reserved By CyberWin Future Software Services Center 2004～2016<a href=\"http://www.ynwlzc.net\">http://www.ynwlzc.net</a><a href=\"http://www.51.la/?17297946\" target=\"_blank\"><img alt=\"我要啦免费统计\" src=\"http://img.users.51.la/17297946.asp\" style=\"border:none\"></a></center>";

            return ret;
        }

        public string CyberDefault(NameValueCollection d)
        {
            string ret = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><title>CyberPHP Handle Server Debug</title></head><body>";
            ret = ret + "<div style=\"height:20px;color:blue;text-align:center;\"><p> hello111111111111</p></div>";
            ret = ret + "<ul>";
            // writer.WriteLine(token);
            ret = ret + "</ul>";
            ret = ret + "<ul>您输入的";
            //  writer.WriteLine(url);
            ret = ret + "<li>网址是：" + d.Get("CyberPHP->Client:URL") + "</li>";
            ret = ret + "<li>路径是：" + d.Get("CyberPHP->Client:Path") + "</li>";
            ret = ret + "<li>文件名：" + d.Get("CyberPHP->Client:FileName") + "</li>";
            ret = ret + "<li>不含文件路径：" + d.Get("CyberPHP->Client:PathWithOutFileName") + "</li>";
            ret = ret + "<li>域名：" + d.Get("CyberPHP->Client:Domain") + "</li>";
            ret = ret + "</ul>";
            ret = ret + "<ul>";
            // writer.WriteLine(req);
            ret = ret + "</ul>";

            NameObjectCollectionBase.KeysCollection theKey;
            theKey = d.Keys; //获取键
            foreach (string key in theKey)
            {
                //循环使用数组
                //Response.Write(key + "<br />");     //返回所有键的名称
                ret = ret + "<ul>";
                // System.Web.HttpContext.Current.Server.UrlDecode(str);
                //  httpListenerContext.Request.s
                ret = ret + "参数" + key + "<br>值" + d[key];
                ret = ret + "</ul>";
            }
            ret = ret + "</body></html>";
            return ret;
        }

        public NameValueCollection CyberPHPGetParm(string input)
        {
            NameValueCollection d = new NameValueCollection();

            string str = input;// "aaajsbbbjsccc";
            string split_param = "CyberPHP->Param:";
            string split_value = "CyberPHP->Value:";
            string[] sArray = Regex.Split(str, split_param, RegexOptions.IgnoreCase);
            int j = 0;
            foreach (string i in sArray)
            {
                // Response.Write(i.ToString() + "<br>");
                string[] valueArrat = Regex.Split(i, split_value, RegexOptions.IgnoreCase);
                if (valueArrat.Length < 2)
                {
                    d.Add(j.ToString(), valueArrat[0]);
                }
                else
                {
                    d.Add(valueArrat[0], valueArrat[1]);
                }
                j = j + 1;
            }
            //输出结果：
            //aaa
            //bbb
            //ccc
            //ccc

            return d;
        }

        public NameValueCollection CyberGetParm(string input)
        {
            NameValueCollection d = new NameValueCollection();
            string[] strR = input.Split('&');
            string[] strP = new string[strR.Length];
            for (int i = 0; i < strR.Length; i++)
            {
                string[] strNv = strR[i].Split('=');
                // System.Web.HttpUtility.UrlDecode(strNv[1]);
                // string[] cr = strNv[1].Split('%');
                //  string value =System.Web.

                d.Add(strNv[0], strNv[1]);

            }

            return d;
        }

        public static string UrlDecodeNo(string str)
        {
            char[] cr = str.ToCharArray();

            byte[] byStr = new byte[cr.Length / 2];

            int j = 0;
            for (int i = 0; i < byStr.Length; i++)
            {
                byStr[i] = byte.Parse(cr[j] + "" + cr[j + 1], System.Globalization.NumberStyles.HexNumber);
                j = j + 2;
            }
            str = System.Text.Encoding.UTF8.GetString(byStr);

            return (str);
        }

        public static string UrlDecode(string str)
        {
            // char[] cr = str.ToCharArray();
            string[] cr = str.Split('%');

            byte[] byStr = new byte[cr.Length / 2];

            int j = 0;
            for (int i = 0; i < byStr.Length; i++)
            {
                byStr[i] = byte.Parse(cr[j] + "" + cr[j + 1], System.Globalization.NumberStyles.HexNumber);
                j = j + 2;
            }
            str = System.Text.Encoding.UTF8.GetString(byStr);

            return (str);
        }

        static string UrlDecode解码(string encodedString)
        {
            StringBuilder result = new StringBuilder();
            int i = 0;

            while (i < encodedString.Length)
            {
                if (encodedString[i] == '%')
                {
                    string hexCode = encodedString.Substring(i + 1, 2);
                    int decimalValue = Convert.ToInt32(hexCode, 16);
                    result.Append((char)decimalValue);
                    i += 3;
                }
                else if (encodedString[i] == '+')
                {
                    result.Append(' ');
                    i++;
                }
                else
                {
                    result.Append(encodedString[i]);
                    i++;
                }
            }

            return result.ToString();
        }
        static string UrlDecodeUtf8解码(string encodedString)
        {
            StringBuilder result = new StringBuilder();
            int i = 0;

            while (i < encodedString.Length)
            {
                if (encodedString[i] == '%')
                {
                    string hexCode = encodedString.Substring(i + 1, 2);
                    byte byteValue = Convert.ToByte(hexCode, 16);
                    result.Append(Encoding.UTF8.GetString(new byte[] { byteValue }));
                    i += 3;
                }
                else if (encodedString[i] == '+')
                {
                    result.Append(' ');
                    i++;
                }
                else
                {
                    result.Append(encodedString[i]);
                    i++;
                }
            }

            return result.ToString();
        }

        public void GetHttpContextCallback(IAsyncResult iar)
        {
            // if (stopped) return;
            HttpListenerContext context = httpListener.EndGetContext(iar);
            httpListener.BeginGetContext(GetHttpContextCallback, null);
            string endPoint = context.Request.RemoteEndPoint.ToString();
            int spIndex = endPoint.IndexOf(":");
            endPoint = endPoint.Substring(0, spIndex);

            /*
            byte[] byts = new byte[Request.InputStream.Length];
            Request.InputStream.Read(byts, 0, byts.Length);
            string req = System.Text.Encoding.Default.GetString(byts);
            req = Server.UrlDecode(req);
             * */

            using (HttpListenerResponse response = context.Response)
            {
                //get 的方式在如下解析即可得到客户端参数及值
                //string userName = context.Request.QueryString["userName"];
                //string password = context.Request.QueryString["password"];
                //string suffix = context.Request.QueryString["suffix"];
                //string adType = context.Request.QueryString["adtype"];//文字,图片,视频
                string token = context.Request.QueryString["token"];
                //  context.Request.
                // string wxi=context.Request.

                StreamReader reader = new StreamReader(context.Request.InputStream);
                string req = reader.ReadToEnd();
                //string req = HttpUtility.UrlDecode(reader.ReadToEnd());  




                HttpListenerContext httpListenerContext = httpListener.GetContext();

                /*
                byte[] byts = new byte[HttpContext.Current.Request.InputStream.Length];
                HttpContext.Current.Request.InputStream.Read(byts, 0, byts.Length);
                string req = System.Text.Encoding.Default.GetString(byts);
                 * */



                httpListenerContext.Response.StatusCode = 200;
                using (StreamWriter writer = new StreamWriter(httpListenerContext.Response.OutputStream))
                {
                    writer.WriteLine("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><title>测试服务器</title></head><body>");
                    writer.WriteLine("<div style=\"height:20px;color:blue;text-align:center;\"><p> hellogrh </p></div>");
                    writer.WriteLine("<ul>");
                    writer.WriteLine(token);
                    writer.WriteLine("</ul>");
                    writer.WriteLine("<ul>");
                    writer.WriteLine(req);
                    writer.WriteLine("</ul>");
                    writer.WriteLine("</body></html>");
                }

            }
        }

        #region "V3缓存机制"
        //v3 加载缓存，直接加载缓存

        /// <summary>
        /// 检测是否存在缓存.
        /// </summary>
        /// <param name="appName">应用程序</param>
        ///  
        private bool Cyber_CallisHaveCache(string appName)
        {
            string cache_path = CyberWin_ROOT_PATH + "/CyberPHP_Cache/" + appName + "_cache.cyberphp";
            return System.IO.File.Exists(cache_path);
        }

        public object Cyber_CallAppCacheV2(string appName, string function, NameValueCollection d)
        {
            try
            {


                if (function == "")
                {
                    function = "start";
                }

                string 缓存路径 = CyberWin_ROOT_PATH + "/CyberPHP_Cache/" + appName + "_cache.cyberphp";




                //传入参数
                object[] objCodeParms = new object[1];
                objCodeParms[0] = d;

                string 反映射缓存路径 = CyberWin_ROOT_PATH + "/CyberPHP_AssemblyCache";


                // Cyber_CallDLL ll = new Cyber_CallDLL();
                //Cyber_CallDLL ll = new Cyber_CallDLL(反映射缓存路径);
                // ll.LoadAssembly(@"" + 缓存路径);
                // string sf = ll.FullName;
                // Object return_invoke = ll.Invoke("CyberPHP_Dynamic.APP", function, objCodeParms);
                // ll.Unload();
                Object return_invoke = "";
                return return_invoke;
            }
            catch (TypeLoadException TLEX)
            {
                return "CyberPHP->ERROR::" + TLEX.Message + " InnerException:" + TLEX.InnerException + " Source:" + TLEX.Source;
            }
            catch (Exception ex)
            {
                return "CyberPHP->ERROR::" + ex.Message + " InnerException:" + ex.InnerException + " Source:" + ex.Source;
            }

        }
        public object Cyber_CallAppCache(string appName, string function, NameValueCollection d)
        {
            return Cyber_CallAppCacheV2(appName, function, d);

            /*
                       try
                       {
                           string 缓存路径 = CyberWin_ROOT_PATH + "/CyberPHP_Cache/" + appName + "_cache.cyberphp";

                           //传入参数
                           object[] objCodeParms = new object[1];
                           objCodeParms[0] = d;



                           //On Error Goto myerr VBConversions Warning: could not be converted to try/catch - logic too complex
                           object returnObj = null;
                           Type t = default(Type);
                           System.Reflection.Assembly systemReflectionAssembly = default(System.Reflection.Assembly);
                           System.Reflection.MethodInfo systemReflectionMethodInfo = default(System.Reflection.MethodInfo);
                           object o = null;
                           //鍒ゆ柇鏂囦欢瀛樺湪

                           //璇诲彇鎸囧畾妯″潡锛屽苟鍔犺浇绋嬪簭闆嗗埌鍐呭瓨
                           systemReflectionAssembly = System.Reflection.Assembly.LoadFile(缓存路径); //鍔犺浇妯″潡

                           //杩斿洖绋嬪簭闆嗘寚瀹氬璞?
                           t = systemReflectionAssembly.GetType("CyberPHP_Dynamic.APP");

                           //鏍规嵁鍓嶉潰t鐨勭被鍨嬪垱寤轰竴涓璞?
                           o = Activator.CreateInstance(t);

                           //e("CyberPHP_Dynamic.APP");
                         //  MethodInfo objMI = objHelloWorld.GetType().GetMethod("start");
                           //杩斿洖鏂规硶淇℃伅
                           systemReflectionMethodInfo = t.GetMethod("start");

                           //璋冪敤鏂规硶
                           returnObj = systemReflectionMethodInfo.Invoke(o, objCodeParms);
                           //杩斿洖璋冪敤缁撴灉

                           //释放缓存
                           //objRemote = null;
                          // AppDomain.Unload(objAppDomain);
                         //  systemReflectionAssembly.
                          // System.Reflection.Assembly.

                           return returnObj;
                       }
                       catch (Exception ex)
                       {
                           return "CyberPHP->ERROR::" + ex.Message + " InnerException:" + ex.InnerException + " Source:" + ex.Source;
                       }
             * */
        }
       
        #endregion
        //V1加载
        public 未来之窗_APP_Config Cyber_CallAppV1Loading(string appName)
        {
            未来之窗_APP_Config app_config = new 未来之窗_APP_Config();
            try
            {
                /*
                  // 3.CompilerParameters

                  CompilerParameters objCompilerParameters = new CompilerParameters();
                  objCompilerParameters.ReferencedAssemblies.Add("System.dll");

                  int i = 1;
                  int l = 1000;
                  string configPath = Application.StartupPath + "/CyberPHP_App/" + action + "_config.cyberphp";
                  if (System.IO.File.Exists(configPath) == false)
                  {
                      l = 1;
                  }

                  CyberWin.CSHARP.HRKJ.WebFrame.CyberPHP.CyberWinWeb.Helper.InfoControl.iniFile ir = new CyberWin.CSHARP.HRKJ.WebFrame.CyberPHP.CyberWinWeb.Helper.InfoControl.iniFile(configPath);
                  for (i = 1; i < l; i++)
                  {
                      //ir.
                      string libstr = ir.IniReadValue("include", i.ToString());// ir.GetINI("include", i.ToString(), "", configPath);
                      libstr = libstr.Replace("{cyberphp_core}", Application.StartupPath + "/CyberPHP_core");
                      if (libstr.Length < 3)
                      {
                          break;
                      }
                      else
                      {
                          objCompilerParameters.ReferencedAssemblies.Add(libstr);
                      }
                  }
                  objCompilerParameters.GenerateExecutable = false;
                  objCompilerParameters.GenerateInMemory = true;

                  // 4.CompilerResults
                  //4.1
                  string codepath = Application.StartupPath + "/CyberPHP_App/" + action + "_app.cyberphp";
                  if (System.IO.File.Exists(codepath) == false)
                  {
                      return "CyberPHP->ERROR:错误的调用";
                  }
                  StreamReader fileStream = new StreamReader(codepath, Encoding.Default);
                  string code = fileStream.ReadToEnd();
                  fileStream.Close();
                   * */
                string file_path_dir = CyberWin_ROOT_PATH + "/" + "CyberWin_App/" + appName + "/";
                if (System.IO.Directory.Exists(file_path_dir) == false)
                {

                    app_config.状态 = 9004;
                    app_config.信息 = "CyberPHP->ERROR:错误的调用";
                    return app_config;
                }
                string file_path_code = CyberWin_ROOT_PATH + "/" + "CyberWin_App/" + appName + "/" + appName + "_app.cyberphp";
                string file_path_lib = CyberWin_ROOT_PATH + "/" + "CyberWin_App/" + appName + "/" + appName + "_config.cyberphp";

                if (System.IO.File.Exists(file_path_code) == false)
                {

                    app_config.状态 = 9004;
                    app_config.信息 = "CyberPHP->ERROR:错误的调用";
                    return app_config;
                }

                //读取扩展代码
                StreamReader fileStream = new StreamReader(file_path_code, Encoding.Default);
                string 扩展代码 = fileStream.ReadToEnd();
                fileStream.Close();

                app_config.code = 扩展代码;//代码片段

                CompilerParameters objCompilerParameters = new CompilerParameters();//加载动态库

                objCompilerParameters.ReferencedAssemblies.Add("System.dll");


                //读取扩展库
                StreamReader fileStream_扩展库 = new StreamReader(file_path_lib, Encoding.Default);
                string 扩展库 = fileStream_扩展库.ReadToEnd();
                fileStream_扩展库.Close();



                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(扩展库);


                XmlNodeList cyberwin_inclist = xmlDoc.SelectNodes("/cyberwin/include/cyber_lib"); //获取person子节点集合  

                //  xmlDoc.SelectNodes("/cyberwin/include");

                foreach (XmlNode node in cyberwin_inclist)
                {
                    string strPath_lib = ((XmlElement)node).GetAttribute("path");   //获取name属性值  
                                                                                    // this.richTextBox2.AppendText("aaaaa"+strPath);
                                                                                    //  this.richTextBox2.AppendText("aaaaa" + node.Attributes["author"].Value);

                    strPath_lib = strPath_lib.Replace("{cyberphp_core}", CyberWin_ROOT_PATH + "/CyberPHP_core");
                    objCompilerParameters.ReferencedAssemblies.Add(strPath_lib);

                }
                objCompilerParameters.GenerateExecutable = false;
                objCompilerParameters.GenerateInMemory = true;
                app_config.objCompilerParameters = objCompilerParameters;

                app_config.状态 = 1;
                app_config.信息 = "CyberPHP->ERROR:调用成功";
                return app_config;




            }
            catch (Exception ex)
            {
                app_config.状态 = 9005;
                app_config.信息 = "CyberPHP->ERROR:unknown" + ex.Message;
                return app_config;
            }
        }
        


             







                #endregion
                #region "系统日志"
                public void writesyslog(string msg, string msgtype)
                {

                    if (msgtype == "1")
                    {
                        writesyslog(msg, EventLogEntryType.SuccessAudit, 9000);
                    }
                    else
                    {
                        writesyslog(msg, EventLogEntryType.FailureAudit, 19007);
                    }
                }

                public void writesyslog(string msg, EventLogEntryType t, int code)
                {
                    EventLog.WriteEntry(log_event, msg, t, code);
            // CyberWin.CSHARP.YNWLZC.WebFrame.CyberPHP.CyberWinOutput.Log.Cyber_Logger.write_log("运行日志", "" + code, msg);
            write_log("运行日志", "" + code, msg);
        }

        //日志
        public static void write_log(string capturetype, string type, string s)
        {
            string logPath = Application.StartupPath + "/log/" + capturetype + "/" + DateTime.Now.ToLongDateString() + "/";
            if (System.IO.Directory.Exists(logPath) == false)
            {
                System.IO.Directory.CreateDirectory(logPath);
            }
            string 文件路径 = logPath + type + "_log.log";

            FileStream fs = new FileStream(文件路径, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            sw.WriteLine("==============================\r\n" + DateTime.Now.ToLongDateString() + "<<<<<<<<<<<<<<<<<<<<<<<<<<");
            sw.WriteLine(s);
            sw.WriteLine("");
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }
        #endregion
    }
        }
    
